package cn.zebra.dev.net.prot;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.Callable;

/**
 * 端口多线程返回任务
 *
 * @author runnable@sina.cn
 */
public class PortTask implements Callable<Port> {

    private String host;

    private Integer port;

    public PortTask(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public Port call() throws Exception {
        Port port = new Port();
        port.setPort(this.port);
        InetAddress inetAddress = InetAddress.getByName(host);
        Socket socket = null;
        try {
            //建立一个Socket连接
            socket = new Socket(inetAddress, this.port);
            port.setFlag(true);
        } catch (IOException e) {
            String message = e.getMessage();
            switch (message) {
                case PortErrorMessageConstant.INVALID:
                    port.setErrorMessage("地址在本地计算机上无效，或端口在远程计算机上无效!");
                    break;
                case PortErrorMessageConstant.REFUSED:
                    port.setErrorMessage("连接被拒绝!");
                    break;
                case PortErrorMessageConstant.PERMISSION_DENIED:
                    port.setErrorMessage("权限被拒绝!");
                    break;
                default:
                    e.printStackTrace();
                    port.setErrorMessage(message);
                    break;
            }
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
        return port;
    }

    public String getHost() {
        return host;
    }

    public Integer getPort() {
        return port;
    }

    @Override
    public String toString() {
        return "PortTask{" +
                "host='" + host + '\'' +
                ", port=" + port +
                '}';
    }
}
